#!/bin/bash

# 配置参数
CONF_DIR="/data/detect/conf"
GLOBAL_CONF="$CONF_DIR/global/conf.yaml"
LOG_DIR="/data/detect/logs"
mkdir -p "$LOG_DIR"

# 启动参数
INITIAL_DELAY=1  # 初始等待时间(秒)
MAX_DELAY=10     # 最大等待时间(秒)

DATA_FILE="/data/detect/share/regedit/reload"

if [ ! -f "$DATA_FILE" ]; then
    echo "错误：配置文件列表 $DATA_FILE 不存在"
    exit 1
fi

echo "准备启动摄像头进程，配置文件列表来源于 $DATA_FILE"

i=0
while read -r CAM_CONF; do
    # 忽略空行
    [ -z "$CAM_CONF" ] && continue

    ((i++))
    CAM_NAME=$(basename "$CAM_CONF" .yaml)
    LOG_FILE="$LOG_DIR/${CAM_NAME}_$(date +%Y%m%d).log"

    echo "[$(date)] 启动摄像头: $CAM_NAME" | tee -a "$LOG_FILE"

    # 检查配置文件是否存在
    if [ ! -f "$CAM_CONF" ]; then
        echo "[$(date)] 错误: 配置文件 $CAM_CONF 不存在" | tee -a "$LOG_FILE"
        continue
    fi

    # 启动进程
    /home/monster/miniconda3/envs/rknn/bin/python main.py \
        --global_conf "$GLOBAL_CONF" \
        --camera_conf "$CAM_CONF" \
        --log_file "$LOG_FILE" >> "$LOG_FILE" 2>&1 &

    # 记录进程ID
    echo $! >> "$LOG_DIR/pids.log"

    # 动态计算等待时间（逐步增加延迟）
    CURRENT_DELAY=$((INITIAL_DELAY + i - 1))
    CURRENT_DELAY=$(( CURRENT_DELAY > MAX_DELAY ? MAX_DELAY : CURRENT_DELAY ))
    echo "[$(date)] 等待 ${CURRENT_DELAY}秒..." | tee -a "$LOG_FILE"
    sleep $CURRENT_DELAY    
done < "$DATA_FILE"

# 清空旧的CONF记录
> "$DATA_FILE"

# 检查实际启动的进程数
RUNNING_PIDS=$(wc -l < "$LOG_DIR/pids.log")
echo "成功启动 $RUNNING_PIDS 个摄像头进程"
